﻿using System;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using TFSTools.TFSLibrary;
using TFSTools.TFSLibrary.TestManagement;

namespace TFSTools.TestManagement.TestCaseReview
{
    /// <summary>
    /// Interaction logic for TestPlanView
    /// </summary>
    public partial class TestPlanView : Window
    {
        #region Data Members

        private bool isFirstTimeActivated = false;

        public TFSConnection Connection { get; set; }

        public TFSTestPlan SelectedTestPlan { get; set; }

        #endregion
        
        #region Constructor
        
        public TestPlanView()
        {
            this.InitializeComponent();
        }

        public TestPlanView(TFSConnection connection)
        {
            this.InitializeComponent();
            this.Connection = connection;
            if (connection != null && connection.IsConnected)
            {
                this.UpdateServerInfo();
                this.isFirstTimeActivated = true;
            }
        }
        
        #endregion
        
        #region Window Events
        
        private void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Connection = TFSConnection.LoadProjectSelectionFromUser();
                this.UpdateServerInfo();

                if (this.Connection != null)
                {
                    var settings = Properties.Settings.Default;
                    settings.TestProject = this.Connection.SelectedProject.Name;
                    settings.TfsUri = this.Connection.ServerUri;
                    settings.Save();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occured.  " + ex.Message);
            }
        }

        private void Window_Activated(object sender, EventArgs e)
        {
            if (this.isFirstTimeActivated)
            {
                return;
            }

            this.isFirstTimeActivated = true;

            this.LoadServerFromSettings();
        }

        private void TestPlansGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.btnSelectPlan.IsEnabled = this.dgTestPlans.SelectedItem is TFSTestPlan;
        }

        private void TestPlansGrid_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (this.btnSelectPlan.IsEnabled)
            {
                this.SelectPlanButton_Click(sender, null);
            }
        }

        private void SelectPlanButton_Click(object sender, RoutedEventArgs e)
        {
            this.SelectedTestPlan = this.dgTestPlans.SelectedItem as TFSTestPlan;

            if (this.SelectedTestPlan != null)
            {
                var settings = Properties.Settings.Default;
                settings.TestPlanId = this.SelectedTestPlan.Id;
                settings.Save();

                this.DialogResult = true;
                this.Close();
            }
            else
            {
                MessageBox.Show("Please select a Test Plan.");
            }
        }
        
        #endregion
        
        #region Private Members

        private void LoadServerFromSettings()
        {
            try
            {
                var settings = Properties.Settings.Default;

                this.SetServerInfoText("Connecting to TFS...");

                if (!string.IsNullOrEmpty(settings.TfsUri) && !string.IsNullOrEmpty(settings.TestProject))
                {
                    this.Connection = new TFSConnection(new Uri(settings.TfsUri), settings.TestProject);
                    this.SetServerInfoText(string.Empty);
                }

                this.UpdateServerInfo();
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occured.  " + ex.Message);
            }
        }

        private void UpdateServerInfo()
        {
            if (this.Connection != null && this.Connection.SelectedProject != null)
            {
                this.UpdateTestPlanList();
            }
            else
            {
                this.SetServerInfoText("Click 'Connect...'");
            }
        }

        private void UpdateTestPlanList()
        {
            this.SetServerInfoText("Retrieving Test Plans");

            var testPlans = this.Connection.TestManagement.TestTeamProject.GetTestPlans().Where(testPlan => testPlan.State == "Active");

            if (testPlans.Any())
            {
                var sortedList = TestPlanSorter.Sort(testPlans.ToList());
                this.dgTestPlans.ItemsSource = sortedList;

                if (this.SelectedTestPlan != null && testPlans.Contains(this.SelectedTestPlan))
                {
                    this.dgTestPlans.SelectedItem = this.SelectedTestPlan;
                }
            }
            else
            {
                MessageBox.Show("This team project does not contain any test plans.");
            }

            this.SetServerInfoText(string.Empty);
        }

        private void SetServerInfoText(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                if (this.Connection != null)
                {
                    if (this.Connection.SelectedProject != null)
                    {
                        this.tbxTFSServerInfo.Text = this.Connection.ServerName + ";" + this.Connection.SelectedProject.Name;
                    }
                    else
                    {
                        this.tbxTFSServerInfo.Text = this.Connection.ServerName;
                    }
                }
            }
            else
            {
                tbxTFSServerInfo.Text = text;
            }

            this.Refresh();
            Thread.Sleep(500);
        }

        #endregion
    }
}
